<template>
	<div>
		<view class="">
			<!-- 头部 -->
			<headervue @getheaderheightdata="getheaderheightdata">
				<template slot="slot1">
					<view class="indexheader-center">
						通讯
					</view>
				</template>
				<template slot="slot2">
					<image @tap="gosearch" class="indexheader-left-img" src="/static/tabBar/index/search.png" mode="">
					</image>
				</template>
				<template slot="slot3">
					<image @tap="gogroup" class="indexheader-left-img" src="/static/tabBar/index/add-account.png"
						mode=""></image>
				</template>
			</headervue>

			<!-- 滚动视图 -->
			<scroll-view scroll-y="true" :style="{ 'margin-top': headerheight + 'px'}">
				<view class="">
					<view class="" @tap="golive">
						<button>
							视频推流
						</button>
					</view>
					<view class="" @tap="goliveplayer">
						<button>
							视频拉流
						</button>
					</view>
					<view class="" @tap="gocallback">
						<button ref="audioRef">
							call页面
						</button>
					</view>
				</view>
				<view class="friendlist">
					<view class="" v-if="handlemessages.length>0">
						<!-- #ifdef APP -->
						<view v-show="false">
							<button ref="playButton" @tap="playVoice()">翘英庄</button>
						</view>
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<view class="page-section page-section-gap" style="text-align: center;">
							<audio style="text-align: left" :src="`${baseurl}${voicePath}`"
								:poster="`${baseurl}${videoimg}`" name='《融风渐暖》' author='未知' action="{method: 'play'}" ref="audioRef"
								></audio>
						</view>
						<!-- #endif -->

						<view class="frienditem" v-for="(item,index) in handlemessages" :key="item.id"
							@tap="frienditem(item)">
							<view class="friendlist-left">
								<image class="friendlist-left-img" :src="`${baseurl}/${item.imgUrl}`" mode=""></image>
								<view class="tip" v-show="item.count != 0">
									{{item.count}}
								</view>
							</view>
							<view class="friendlist-right">
								<view class="friendlist-right-top">
									<view class="name">
										{{item.nickname}}
									</view>
									<view class="time">
										{{item.formattedTime || item.time}}
									</view>
								</view>
								<view class="friendlist-right-bottom">

									<view v-if="item.types == 0">
										{{item.message}}
									</view>
									<view v-else-if="item.types ==1">
										[图片]
									</view>
									<view v-else-if="item.types == 3">
										[ 定位 ]
									</view>
									<view v-else>
										一段音频
									</view>
								</view>
							</view>


						</view>
						<view class="">
							<uni-group title="群消息" margin-top="20">
								<view class="frienditem" v-for="(item,index) in grouplistdetail"
									@tap="gogroupmessage(item)">
									<view class="friendlist-left">
										<image class="friendlist-left-img" :src="`${baseurl}/${item.imgurl}`"
											mode="aspectFill"></image>
										<view class="tip" v-show="item.count != 0">
											0
										</view>
									</view>
									<view class="friendlist-right">
										<view class="friendlist-right-top">
											<view class="name">
												{{item.groupname == null ? item.groupschema_name : item.groupname}}
											</view>
											<view class="time">
												{{item.formattedTime || item.time}}
											</view>
										</view>
										<view class="friendlist-right-bottom">
											<view v-if="item.types == 0">
												{{item.message}}
											</view>
											<view v-else-if="item.types ==1">
												[图片]
											</view>
											<view v-else-if="item.types == 3">
												[ 定位 ]
											</view>
											<view v-else>
												一段音频
											</view>
										</view>
									</view>
								</view>
							</uni-group>
						</view>
					</view>

					<view class="" v-else>
						<!-- #ifdef APP -->
						<!-- <view v-show="false">
							<button ref="playButton" @tap="playVoice(voicePath)">翘英庄</button>
						</view> -->
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<view class="page-section page-section-gap" style="text-align: center;">
							<audio style="text-align: left" :src="`${baseurl}${voicePath}`"
								:poster="`${baseurl}${videoimg}`" name='《融风渐暖》' author='未知' action="{method: 'play'}"></audio>
						</view>
						<!-- #endif -->
						<view style="height: 85vh;margin-top: 1%">

							<uni-section title="你还没有朋友哦~!" type="line">
								<uni-card>
									<image src="@/static/49dbcfe7b77748908e2fcbfe78042d71.gif" style="width: 100%;">
									</image>
									<text class="uni-body">快去玩玩(┭┮﹏┭┮)加点上你的好朋友~!!</text>
									<view slot="actions">
										<view class="card-actions-item" @click="actionsredo('redo')">
											<uni-icons type="redo" size="24" color="#61afef"></uni-icons>
											<text class="card-actions-item-text">分享我的名片</text>
										</view>
										<view class="card-actions-item" @click="actionsredo('staff')">
											<uni-icons type="staff" size="24" color="#fda700"></uni-icons>
											<text class="card-actions-item-text">去加好友</text>
										</view>
										<view class="card-actions-item" @click="actionsredo('eye')">
											<uni-icons type="eye" size="24" color="#5bca34"></uni-icons>
											<text class="card-actions-item-text">查看个人名片</text>
										</view>
									</view>
								</uni-card>
							</uni-section>
							<view v-if="isShow" class="reserva-detal" @touchmove.stop.prevent="">
								<!-- 阴影框 -->
								<view class="pop-mask" @tap="hidePop()">
								</view>
								<view class="pop-box" :animation="animationData">
									<view class="pop-btitle">
										<view class="pop-item">
											<view class="" v-for="(item,index) in list" :key="item.id"
												@click="gosharelist(item.id)">
												<image style="width: 100rpx;height: 100rpx;padding:30rpx 50rpx;"
													:src="item.img" mode=""></image>

												<view class="pop-item-title">
													{{item.title}}
												</view>
											</view>

										</view>
									</view>

									<view class="pop-sub" @tap="gocancel">
										取消
									</view>
								</view>
							</view>
						</view>
					</view>


				</view>
			</scroll-view>

		</view>
		<view class="">
			<tarbar currentPage="index"></tarbar>
		</view>
	</div>
</template>

<script>
	import tarbar from '@/common/tabbar.vue'
	import headervue from '../../components/header/index.vue'
	import $http from '@/common/api/request.js'
	import {
		mapState
	} from 'vuex'
	import 'intl';
	import 'intl/locale-data/jsonp/zh';
	import _ from 'lodash';
	const innerAudioContext = uni.createInnerAudioContext();
	export default {
		data() {
			return {
				headerheight: 0,
				friendlist: [], //用于渲染列表
				idArray: [], //传递给后端的好友数组
				unreadmsg: [], //消息数
				baseurl: "https://zyc618.mynatapp.cc",
				voicePath: "",
				videoimg: "",
				tosolvetye: "",
				isShow: false,
				grouplistdetail: [],
				animationData: {}, //动画过渡
				list: [{
						id: 0,
						title: "微信好友",
						img: "../../static/weixin.jpg"
					},
					{
						id: 1,
						title: "微信朋友圈",
						img: "../../static/friend.jpg"
					},
					{
						id: 2,
						title: "微信收藏",
						img: "../../static/linka.jpg"
					},
					{
						id: 3,
						title: "新浪微博",
						img: "../../static/weibo.jpg"
					},
					{
						id: 4,
						title: "QQ",
						img: "../../static/qq.jpg"
					},
					{
						id: 5,
						title: "商品二维码",
						img: "../../static/shop.jpg"
					},
				]
			}
		},
		methods: {
			//前往视频按钮:
			goliveplayer() {
				uni.navigateTo({
					url: '/pages/liveplayer/liveplayer'
				})
			},
			golive() {
				uni.navigateTo({
					url: '/pages/live/live'
				})
			},
			gocallback() {
				uni.navigateTo({
					url: '/pages/call/call'
				})
			},
			//点击朋友类别:
			frienditem(item) {
				//发起请求将所有未读记录清除:

				if (item.count == 0) {
					uni.navigateTo({
						url: `/pages/messagespage/messagespage?friendNickname=${item.nickname}&friendID=${item.friendID}&pathavatar=${item.imgUrl}`
					})
				} else {
					this.updatemsg(item.friendID, item);
				}
			},
			//发起请求将所有未读记录清除:
			updatemsg(index, item) {
				$http.request({
					url: "/index/updatemsg",
					method: "post",
					data: {
						userID: this.userInfo.id,
						friendID: index
					}
				}).then((res) => {
					console.log(res);
					if (res.code == 200) {
						this.$nextTick(() => {
							this.navigateTo({
								url: `/pages/messagespage/messagespage?friendNickname=${item.nickname}&friendID=${item.friendID}&pathavatar=${item.imgUrl}`
							})
						})
					}
				}).catch(() => {

				})
			},
			//前往搜索页面
			gosearch() {
				this.navigateTo({
					url: "/pages/list1/list1"
				})
			},

			gogroup() {
				if (this.friendlist.length !== 0) {
					this.navigateTo({
						url: `/pages/creatgroup/creatgroup?friendlist=${JSON.stringify(this.friendlist)}`
					})
				} else {
					this.navigateTo({
						url: `/pages/creatgroup/creatgroup?friendlist=${JSON.stringify([this.userInfo])}`
					})
				}

			},
			getheaderheightdata(heig) {
				this.headerheight = heig
			},
			//获取朋友列表数据:
			getfriend() {
				$http.request({
					url: "/index/getfriend",
					method: "POST",
					data: {
						UserID: this.userInfo.id,
						state: 0
					}
				}).then((res) => {

					if (res.code == 200) {
						// console.log(res.data);
						this.idArray = res.data.map(item => item.id);

						this.getlastmsg();
						this.getupdatemsg();

					}
				}).catch((err) => {
					console.log(err);
				})
			},
			//获取最后一条聊天数据:
			getlastmsg() {
				$http.request({
					url: "/index/getlastmsg",
					method: "POST",
					data: {
						userID: this.userInfo.id,
						friendID: JSON.stringify(this.idArray),
					}
				}).then((res) => {


					if (res.code == 200) {
						this.friendlist = res.data;

					}
				}).catch((err) => {
					console.log(err);
				})
			},
			//获取未读消息数:
			getupdatemsg() {
				$http.request({
					url: "/index/unreadmsg",
					method: "POST",
					data: {
						userID: this.userInfo.id,
						friendID: JSON.stringify(this.idArray),
					}
				}).then((res) => {
					if (res.code == 200) {
						this.unreadmsg = res.data;


					}
				}).catch((err) => {
					console.log(err);
				})
			},
			//时间处理函数
			parseChineseDate(dateStr) {
				const [, year, month, day, hours, minutes] = dateStr.match(/(\d{4})年(\d{2})月(\d{2})日(\d{2}):(\d{2})/);
				return new Date(`${year}/${month}/${day} ${hours}:${minutes}`);
			},
			isSameDay(date1, date2) {
				return (
					date1.getDate() === date2.getDate() &&
					date1.getMonth() === date2.getMonth() &&
					date1.getFullYear() === date2.getFullYear()
				);
			},
			isYesterday(date1, date2) {
				const yesterday = new Date(date1);
				yesterday.setDate(date1.getDate() - 1);

				return (
					yesterday.getDate() === date2.getDate() &&
					yesterday.getMonth() === date2.getMonth() &&
					yesterday.getFullYear() === date2.getFullYear()
				);
			},
			isSameYear(date1, date2) {
				return date1.getFullYear() === date2.getFullYear();
			},
			isValidDate(date) {
				return !isNaN(date.getTime());
			},
			formatTime(date) {
				const options = {
					hour: '2-digit',
					minute: '2-digit'
				};
				return new Intl.DateTimeFormat('zh-CN', options).format(date);
			},
			formatSameYearDate(date) {
				const options = {
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit'
				};
				return new Intl.DateTimeFormat('zh-CN', options).format(date);
			},
			getheightbottom(heighttotle) {
				this.getheightelement = heighttotle;
			},
			actionsredo(stringstr) {
				if (stringstr == "staff") {
					this.navigateTo({
						url: "/pages/list1/list1"
					})
				} else if (stringstr == "redo") {
					this.isShow = true

				} else {
					this.navigateTo({
						url: `/pages/gofrienddetailpage/gofrienddetailpage?friendID=${this.userInfo.id}`
					})
				}
			},
			//获取背景音乐音频:
			getMP3() {
				$http.request({
					url: "/getmp3music",
					method: "POST",
				}).then((res) => {

					if (res.code == 200) {

						this.voicePath = res.data.success;
						this.videoimg = res.data.videoimg;
					}
				}).catch((err) => {
					console.log(err);
				})
			},
			//背景音乐播放:
			playVoice() {
				
				innerAudioContext.autoplay = true; //自动播放
				innerAudioContext.loop = true; //是否循环播放
				// 音频路径
				innerAudioContext.src = `${this.baseurl}${this.voicePath}`;
				// 开始播放的位置
				innerAudioContext.startTime = 0
				//播放音量
				innerAudioContext.volume = 1
				innerAudioContext.play();
			},
			stopVoice(){
				innerAudioContext.autoplay = false; //自动播放
				innerAudioContext.loop = false; //是否循环播放
				innerAudioContext.volume = 0
				innerAudioContext.stop();
			},
			formatDateTime(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const seconds = date.getSeconds().toString().padStart(2, '0');
				return `${hours}:${minutes}:${seconds}`;
			},
			//写一个方法:
			// 防抖unshift事件处理函数:
			handleDebouncedClick: _.debounce((index, updatedObject) => {
				this.$set(this.handlemessages, index, updatedObject);
				this.$forceUpdate();
			}, 1000),
			changesavemsg(datamessage) {
				const index = this.updatedFriendlist.findIndex(obj => obj.friendID === Number(datamessage.userID));
				if (index !== -1) {
					const updatedObject = {
						...this.handlemessages[index],
						message: datamessage.message,
						formattedTime: datamessage.time,
						count: this.handlemessages[index].count + 1
					};

					// Update the array at the specific index
					this.handleDebouncedClick(index, updatedObject)
				}
			},
			//socket后端返回的数据接收:fromid用户发送:  接收方
			receiveSocketMsg(type) {
				this.socket.on("msg", (msg, fromid, tosolvetye) => {
					if (tosolvetye == (1 || 2)) { //图片为1
						let datamessage = {
							userID: fromid, //发送方的id
							// imgurl:`${this.baseurl}${this.userInfo.imgUrl}`,//先写自己的头像
							message: `${tosolvetye = 1 ? '图片':'音频'} '`,
							types: tosolvetye, //
							time: this.formatDateTime(new Date()),
							id: String(new Date().getTime()) + String(Math.floor(Math.random() * 1000))
						};
						this.changesavemsg(datamessage)
					} else { //文字为2
						let datamessage = {
							userID: fromid, //?
							// imgurl:`${this.baseurl}${this.userInfo.imgUrl}`,//先写自己的头像
							message: JSON.parse(msg),
							types: tosolvetye, //
							time: this.formatDateTime(new Date()),
							id: String(new Date().getTime()) + String(Math.floor(Math.random() * 1000))
						};

						this.changesavemsg(datamessage)
					}
				})
			},
			//类型模板函数:
			thealldatamessage(type, data) {
				this.tosolvetye = type;
				this.receiveSocketMsg(type);
			},
			//````事件总线
			getstringmsg() {
				uni.$on('getstringmsg', data => {
					this.thealldatamessage(0, data);
				})
			},
			//文件
			getphotomsg() {
				uni.$on('getfilepaths', data => {
					this.thealldatamessage(1, data);
				})
			},
			//音频
			getMP3msg() {
				uni.$on('getlocationdetail', data => {
					this.thealldatamessage(2, data);
				})
			},
			//分享功能:
			hidePop() {
				var animation = uni.createAnimation({
					duration: 200,
				})
				animation.translateY(0).step()
				this.animationData = animation.export()
				setTimeout(() => {
					animation.translateY(600).step()
					this.isShow = false;
				}, 200)

			},
			//分享列表:
			gosharelist(index) {
				if (index === 0) {
					this.shareall("weixin", "WXSceneSession")
				} else if (index === 1) {
					this.shareall("weixin", "WXSceneTimeline")
				} else if (index === 2) {
					this.shareall("weixin", "WXSceneFavorite")
				} else if (index === 3) {
					this.shareall("sinaweibo", "")
				} else if (index === 4) {
					this.shareall("qq", "")
				} else if (index === 5) {
					this.shareall("weixin", "WXSceneSession")
				}

			},
			//分享详细点击:
			shareall(provider, scene) {
				uni.share({
					provider: provider, //微信
					type: 0,
					scene: scene, //WXSceneSession
					title: "看看我的~",
					summary: `快乐看看我的名片吧，赶紧跟我一起来体验`,
					href: `http://static-mp-2e755dd3-d040-486e-a83c-fb05284caad4.next.bspapp.com/#/pages/gofrienddetailpage/gofrienddetailpage?friendID=${this.userInfo.id}`,
					imageUrl: this.baseurl + this.userInfo.imgUrl,
					success: function(res) {
						uni.showToast({
							title: "分享成功",
							icon: "none"
						})
					},
					fail: function(err) {

						uni.showToast({
							title: "答辩项目就不要测试分享了" + "API `share` is not yet implemented"
						})
					}
				})
			},
			gocancel() {
				this.isShow = false;
			},
			//获取群的信息:
			getgrouplist() {
				$http.request({
					url: "/index/getgrouplist",
					method: "POST",
					data: {
						userID: this.userInfo.id,
					}
				}).then((res) => {

					if (res.code == 200) {
						this.grouplistdetail = res.data
						// this.grouplistdetail.forEach(item=>{

						// })
					}
				}).catch((err) => {
					console.log(err);
				})
			},
			gogroupmessage(item) {
				let groupname = item.groupname == null ? item.groupschema_name : item.groupname;
				uni.navigateTo({
					url: `/pages/groupmessage/groupmessage?groupid=${item.groupid}&name=${groupname}&backimg=${item.imgurl}`
				})
			},
			//后台发送过来的livemessage 邀请
			socket_livemessage(){
				this.socket.on('livemessage',(data)=>{
					
					this.$nextTick(() => {
						this.navigateTo({
							url:`/pages/call/call?dataliveinfo=${data}`
						})
					});
					
				})
			},
			
		},
		//组件集合
		components: {
			tarbar,
			headervue
		},
		//计算属性:
		computed: {
			...mapState({
				userInfo: state => state.user.userInfo
			}),
			//计算属性消息数与好友匹配
			updatedFriendlist() {

				return this.friendlist.map(friend => {
					const matchingUnread = this.unreadmsg.find(msg => Number(msg.friendID) === friend.friendID);

					return {
						...friend,
						count: matchingUnread ? matchingUnread.count : 0,
					};
				});
			},
			//时间处理
			handlemessages() {
				const currentDate = new Date();
				return this.updatedFriendlist.map(item => {
					// 复制对象，保留其他属性不变
					const newItem = {
						...item
					};
					const inputDateTime = this.parseChineseDate(item.time);
					// 检查日期字符串是否有效
					if (this.isValidDate(inputDateTime)) {
						// 仅当日期为今天时返回 "10:33"
						if (this.isSameDay(currentDate, inputDateTime)) {
							newItem.formattedTime = this.formatTime(inputDateTime);
						}
						// 仅当日期为昨天时返回 "昨天10:33"
						else if (this.isYesterday(currentDate, inputDateTime)) {
							newItem.formattedTime = '昨天' + this.formatTime(inputDateTime);
						}
						// 仅当日期为同一年时返回 "01月20日10:33"
						else if (this.isSameYear(currentDate, inputDateTime)) {
							newItem.formattedTime = this.formatSameYearDate(inputDateTime);
						}
						// 非本年的消息保持 time 属性不变
						else {
							newItem.formattedTime = item.time;
						}
					}
					return newItem;
				});
			},

		},
		onLoad() {
			this.receiveSocketMsg();
			this.socket_livemessage();//视频socket通讯
			this.getgrouplist()
			//下拉刷新
			setTimeout((options) => {
				this.getfriend();
				this.getMP3();
			}, 200);


			uni.startPullDownRefresh();
		},
		//结束下拉刷新:
		onPullDownRefresh() {
			setTimeout(() => {

				uni.stopPullDownRefresh();
			}, 1000);
		},
		mounted() {
			//登录分配模块:
			this.socket.emit('logintext', this.userInfo.id);

		},
		//事件总线:
		created() {
			//0文字1图片2音频
			//事件总线:获取地图详细坐标:
			uni.$on('getlocationdetail', (data) => {
				this.locationdata = JSON.parse(data);
			})

			//获取输入框内容:
			this.getstringmsg();
			//获取文件地址:
			this.getphotomsg();
			//获取音频地址:
			this.getMP3msg();
			uni.$on('changecontrolsmusic', (data) => {
				this.playVoice();
			})
			uni.$on('offcontrolsmusic', (data) => {
				
				this.stopVoice()
			})
		},
	};
</script>
<style lang="scss">
	.status_bar {}

	.indexheader-center {
		position: absolute;
		right: 50%;
		top: 30%;
	}

	.indexheader-left-img {
		padding-top: (safe-area-inset-top);
		width: 48rpx;
		height: 48rpx;

	}

	.friendlist {
		position: relative;
		width: 100%;

		.frienditem {
			display: flex;
			margin-top: 14rpx;

			.friendlist-left {
				padding-left: 10rpx;
				position: relative;

				// 图片
				.friendlist-left-img {
					width: 126rpx;
					height: 126rpx;
					border-radius: $uni-border-radius-base;
				}

				// 消息框
				.tip {
					z-index: 10;
					position: absolute;
					top: -6rpx;
					left: 110rpx;
					min-width: 36rpx;
					height: 36rpx;
					background-color: $uni-color-warning;
					border-radius: $uni-border-radius-circle;
					font-size: $uni-font-size-sm;
					color: $uni-text-color-inverse;
					line-height: 36rpx;
					text-align: center;
				}
			}

			.friendlist-right {
				padding: 0rpx 20rpx 10rpx;
				width: 100%;

				.friendlist-right-top {
					height: 50rpx;

					.name {
						float: left;
						font-size: 36rpx;
						font-weight: 400;
						color: $uni-text-color;
						line-height: 50rpx;
					}

					.time {
						float: right;
						color: $uni-text-color-disable;
						font-size: $uni-font-size-sm;
						line-height: 50rpx;
					}
				}

				.friendlist-right-bottom {
					font-size: $uni-font-size-base;
					color: $uni-text-color-grey;
					padding: 20rpx 0;
					line-height: 40rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 1;
					overflow: hidden;
				}
			}
		}
	}

	.reserva-detal {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: 999;

		.pop-mask {
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, .6);
		}

		.pop-box {
			position: absolute;
			left: 0;
			bottom: 0;
			width: 100%;
			background-color: #ffffff;
			border-radius: 30rpx;

			.pop-btitle {
				height: 450rpx;

				.pop-item {
					display: flex;
					flex-wrap: wrap;
					justify-content: center;
					align-items: center;

					.pop-item-title {
						display: flex;
						justify-content: center;
						align-items: center;
					}
				}
			}


			.pop-sub {
				z-index: 9999;
				line-height: 80rpx;
				text-align: center;
				margin-bottom: 120rpx;
			}
		}
	}
</style>